package com.tgy.leetcode.backtracking;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: tgy
 * @Date: 2020-11-22 14:32
 */
public class _15_三数之和_01 {

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> lists = new LinkedList<>();
        if (nums == null || nums.length == 0) {

            return lists;
        }

        Arrays.sort(nums);

        int count = 0;

        for (int i = 0; i < nums.length - 2; i++) {

            int sum;
            int left = i + 1, right = nums.length  - 1;

            if (nums[i] > 0) {

                break;
            }



            if (i > 0 && nums[i - 1] == nums[i]) {

                continue;
            }


            while (true) {

                sum = nums[i] + nums[left] + nums[right];
                count++;
                if (sum == 0) {

                    lists.add(Arrays.asList(nums[i], nums[left],nums[right]));
                }

                // 最大值小于0，就不可能是的小于这个值的三个元素之和为 0
                if (nums[right] < 0) {

                    break;
                }

                left++;
                while (left < right && nums[left - 1] == nums[left]) {

                    left++;
                }

                if (sum > 0 || left == right) {

                    right--;
                    // 去除相同的元素
                    while (right > i + 1 && nums[right] == nums[right + 1]) {

                        right--;
                    }

                    if (right < i + 2) {

                        break;
                    }

                    // left 设置为初始值
                    left = i + 1;
                }
            }
        }

        System.out.println(count);

        return lists;
    }
}
